<template>
  <el-drawer
    v-model="drawer"
    :title="title"
    :direction="direction"
    :close-on-click-modal="closeOnClickModal"
    size="70%"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" label-position="right">
      <el-form-item label="模版名称" prop="feightTemplateName" :label-width="formLabelWidth">
        <el-input v-model="form.feightTemplateName" autocomplete="off" placeholder="请输入模版名称" clearable />
      </el-form-item>
      <el-form-item label="包邮方式" prop="parcelType" :label-width="formLabelWidth">
        <el-radio-group v-model="form.parcelType" @change="parcelTypeChange">
          <el-radio value="0" size="large">全国包邮</el-radio>
          <el-radio value="1" size="large">部分包邮</el-radio>
          <el-radio value="2" size="large">自定义</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.parcelType !== '0'" label="计费方式" prop="chargingType" :label-width="formLabelWidth">
        <el-radio-group v-model="form.chargingType" @change="chargingTypeChange">
          <el-radio value="0" size="large">按件数</el-radio>
          <el-radio value="1" size="large">按重量</el-radio>
          <el-radio value="2" size="large">按体积</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.parcelType !== '0'" label="运费" prop="feightPrice" :label-width="formLabelWidth">
        <el-table :data="feightPriceData" style="width: 100%" border stripe>
          <el-table-column property="transportToIds" label="运送到" width="230">
            <template #default="scope">
              <span v-if="scope.row.transportToIds === '0'">默认运费</span>
              <el-cascader
                v-else
                v-model="scope.row.transportToIds"
                :options="cityData"
                :props="props"
                collapse-tags
                collapse-tags-tooltip
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column property="firstFeight" :label="firstFeightLabel" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.firstFeight" :min="1" size="small" />
            </template>
          </el-table-column>
          <el-table-column property="feight" :label="feightLabel" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.feight" :min="0" size="small" />
            </template>
          </el-table-column>
          <el-table-column property="continuation" :label="continuationLable" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.continuation" :min="1" size="small" />
            </template>
          </el-table-column>
          <el-table-column property="renew" :label="renewLable" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.renew" :min="0" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button v-if="scope.row.transportToIds !== '0'" size="small" type="danger" @click="handleFeightDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button style="margin-top: 10px;" type="primary" @click="addFeight" :icon="EditPen">添加区域</el-button>
      </el-form-item>
      <el-form-item v-if="form.parcelType === '2'" label="包邮区域" prop="parcel" :label-width="formLabelWidth">
        <el-table :data="parcelData" style="width: 100%" border stripe>
          <el-table-column property="transportToIds" label="选择区域">
            <template #default="scope">
              <el-cascader
                v-model="scope.row.transportToIds"
                :options="cityData"
                :props="props"
                collapse-tags
                collapse-tags-tooltip
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column property="firstFeight" label="包邮体积（m³）">
            <template #default="scope">
              <el-input-number v-model="scope.row.parcelWeight" :min="1" size="small" />
            </template>
          </el-table-column>
          <el-table-column property="feight" label="包邮金额（元）">
            <template #default="scope">
              <el-input-number v-model="scope.row.parcelPrice" :min="1" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleParcelDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button style="margin-top: 10px;" type="primary" @click="addParcel" :icon="EditPen">添加指定包邮区域</el-button>
      </el-form-item>
      <el-form-item label="排序" prop="sort" :label-width="formLabelWidth">
        <el-input-number v-model="form.sort" :min="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import { ElInput, ElMessageBox } from 'element-plus'
  import { EditPen } from '@element-plus/icons-vue'
  import { getCitys, saveOrUpdate, getFeightTemplateInfo } from '~/api/delivery/feight.js'
  const emit = defineEmits(['refreshDataList'])

  const drawer = ref(false) // el-drawer是否打开
  const title = ref('运费模版') // 标题
  const direction = ref('rtl') // Drawer 打开的方向
  const closeOnClickModal = ref(false) // 是否可以通过点击 modal 关闭 Drawer
  const feightPriceData = ref([]) // 运费表格的数据
  const cityData = ref([]) // 运送到的数据
  const firstFeightLabel = ref('首件')
  const feightLabel = ref('运费（元）')
  const continuationLable = ref('续件')
  const renewLable = ref('续费（元）')
  const parcelData = ref([]) // 选择区域表格的数据
  const formRef = ref(null)
  const props = { 
    multiple: true,
    value: 'id',
    label: 'name',
    children: 'children'
  } // el-cascader是否可以多选
  const form = reactive({
    id: 0,
    feightTemplateName: '',
    parcelType: '0',
    chargingType: '0',
    feightPrice: [],
    parcel: [],
    sort: 0
  })
  const rules = {
    feightTemplateName: [
      { required: true, message: '模版名称不能为空!', trigger: 'blur' }
    ],
    parcelType: [
      { required: true, message: '包邮方式不能为空!', trigger: 'blur' }
    ],
    chargingType: [
      { required: true, message: '计费方式不能为空!', trigger: 'blur' }
    ]
  }

  // el-drawer关闭前的回调，会暂停 Drawer 的关闭
  function handleClose() {
    drawer.value = false
  }
  // 初始化init方法
  function init(id) {
    drawer.value = true
    if(id) {
      // 修改 
      getFeightTemplateInfo(id).then(res => {
        if(res && res.data.code === 200) {
          const data = res.data.data
          form.id = data.id
          form.feightTemplateName = data.feightTemplateName
          form.parcelType = data.parcelType + ''
          form.sort = data.sort
          if(data.parcelType === '1') {
            form.chargingType = data.chargingType
            feightPriceData.value = data.feightPrice
          } else if(data.parcelType === '2') {
            form.chargingType = data.chargingType
            data.feightPrice.forEach((item, index) => {
              if(item.transportToIds.length <= 0) {
                item.transportToIds = '0'
              }
            })
            feightPriceData.value = data.feightPrice
            parcelData.value = data.parcel
          }
        }
      })
    } else {
      // 添加
      form.id = 0
      form.feightTemplateName = ''
      form.parcelType = '0'
      form.chargingType = '0'
      form.feightPrice = []
      form.parcel = []
      form.sort = 0
    }
    // 查询省市及联的数据
    getCitys().then(res => {
      if(res && res.data.code === 200) {
        cityData.value = res.data.data
      }
    })
  }
  // 取消按钮
  function cancelClick() {
    drawer.value = false
  }
  // 确定按钮
  function confirmClick() {
    // 分三种保存方式
    let data = {}
    data.id = form.id
    data.feightTemplateName = form.feightTemplateName
    data.parcelType = form.parcelType
    data.sort = form.sort
    if(form.parcelType === '0') {
      // 1.全国包邮
    } else if(form.parcelType === '1') {
      // 2.部分包邮
      data.feightPrice = feightPriceData.value
      data.chargingType = form.chargingType
    } else {
      // 3.自定义
      data.chargingType = form.chargingType
      feightPriceData.value.forEach((item, index) => {
        if(item.transportToIds === '0') {
          item.transportToIds = []
        }
      })
      data.feightPrice = feightPriceData.value
      data.parcel = parcelData.value
    }
    formRef.value.validate((valid) => {
      if(!valid) {
        return false
      }
      ElMessageBox.confirm(`确定进行保存操作?`, '提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        saveOrUpdate(data).then(res => {
          if(res && res.data.code === 200) {
            drawer.value = false
            emit('refreshDataList')
          } else {
            showMessage(res.data.message, 'error')
          }
        })
      }).catch(err => {
        console.log(err)
      })
    })
  }
  // 运费删除按钮
  function handleFeightDelete(row) {
    let newArray = feightPriceData.value.filter(item => item.transportToIds !== row.transportToIds)
    feightPriceData.value = newArray
  }
  // 添加区域按钮
  function addFeight() {
    feightPriceData.value.push({
        transportToIds: '',
        firstFeight: '1',
        feight: '0',
        continuation: '1',
        renew: '0'
      })
  }
  // 包邮方式删除按钮
  function handleParcelDelete(row) {
    let newArray = parcelData.value.filter(item => item.transportToIds !== row.transportToIds)
    parcelData.value = newArray
  }
  // 添加指定包邮区域按钮
  function addParcel() {
    parcelData.value.push({
      transportToIds: '',
      parcelWeight: '',
      parcelPrice: ''
    })
  }
  // 包邮方式改变时的事件
  function parcelTypeChange(val) {
    form.parcelType = val
    if(val === '2') {
      // 如果包邮方式为自定义的话，初始化表格的值
      feightPriceData.value = [
        {
          transportToIds: '0',
          firstFeight: '1',
          feight: '0',
          continuation: '1',
          renew: '0'
        }
      ]
    } else if(val === '1') {
      feightPriceData.value = [
        {
          transportToIds: '',
          firstFeight: '1',
          feight: '0',
          continuation: '1',
          renew: '0'
        }
      ]
    } else {
      feightPriceData.value = []
    }
  }
  // 计费方式改变时的事件
  function chargingTypeChange(val) {
    if(val === '0') {
      firstFeightLabel.value = '首件'
      feightLabel.value = '运费（元）'
      continuationLable.value = '续件'
      renewLable.value = '续费（元）'
    } else if(val === '1') {
      firstFeightLabel.value = '首件重量（kg）'
      feightLabel.value = '运费（元）'
      continuationLable.value = '续件重量（kg）'
      renewLable.value = '续费（元）'
    } else {
      firstFeightLabel.value = '首件体积（m³）'
      feightLabel.value = '运费（元）'
      continuationLable.value = '续件体积（m³）'
      renewLable.value = '续费（元）'
    }
  }

  // 将方法暴露给父组件
  defineExpose({
    init
  })
</script>
<style>

</style>